import { use, useRef, useState,useEffect } from 'react';
import { Input, Button } from 'antd-mobile';
import './index.css';

function StreamComponent() {
  const token = localStorage.getItem('token');
  const inputRef = useRef(null);
  const aiRef = useRef(null);
  const [messages, setMessages] = useState([]); // 存储所有消息
  const [isReceiving, setIsReceiving] = useState(false); // 标记是否正在接收AI回复
  useEffect(() => {
    console.log(messages);
  }, [messages]);
  const sendai = () => {
    const message = inputRef.current.value;
    if (message) {
      // 添加用户消息
      setMessages(prev => [...prev, { content: message, type: 'user' }]);
      aisay(message);
      inputRef.current.value = '';
    }
  }

  const aisay = async (message) => {
    setIsReceiving(true);
    // 添加一个空的AI消息占位
    setMessages(prev => [...prev, { content: '', type: 'ai', isStreaming: true }]);
    
    try {
      const response = await fetch('/api/api/auth/ai/chat-memory', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${localStorage.getItem('token')}`,
        },
        body: JSON.stringify({ message: message, token: token }),
      });

      const reader = response.body.getReader();
      const decoder = new TextDecoder('utf-8');
      let accumulatedContent = '';
      
      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        
        const chunk = decoder.decode(value);
        const lines = chunk.split('\n');
        console.log('lines',lines);
        lines.forEach((line) => {
          if(line == ''){
            accumulatedContent += '\n';
          }else{
            accumulatedContent += line;
          }
            // 更新最新的AI消息
            setMessages(prev => {
              const newMessages = [...prev];
              const lastMessage = newMessages[newMessages.length - 1];
              if (lastMessage.type === 'ai') {
                lastMessage.content = accumulatedContent;
                console.log('lastMessage',lastMessage);
              }
              return newMessages;
            });
          }
        );
      }
    } finally {
      setIsReceiving(false);
    }
  }

  return (
    <div>
      <div className='content'>
        {messages.map((msg, index) => (
          <div key={index} className={`message-container ${msg.type}-message`}>
            <div className={`message-bubble ${msg.type}-bubble`}>
              {msg.content}
              {msg.isStreaming && isReceiving && <span className="typing-indicator">●●●</span>}
            </div>
          </div>
        ))}
        <div ref={aiRef} ></div>
      </div>
      <div className='input-box'>
        <input
          ref={inputRef}
        />
        <Button onClick={sendai} color='warning'>发送</Button>
      </div>
    </div>
  );
}

export default StreamComponent;